#!/usr/bin/env python3
# -*- coding:utf-8 -*-

import time
import socket
from multiprocessing.dummy import Pool
from random import random


class NmapMe:
    global open_list
    open_list = []

    def __init__(self, ip: str):
        self.ip = ip
        self.port_list = None

    def run_nmapme(self):
        """
        多线程启动扫描端口
        :return:
        """
        print(self.ip)
        if self.ip == None:
            print("请重新获取IP")
            return
        with open('MOMA_V1/data/txt/ports.txt', "r") as port:
            self.port_list = port.read().split('\n')
            pool = Pool(150)
            t1 = time.time()
            for ports in self.port_list:
                pool.apply_async(self.get_port, (ports,))
            pool.close()
            pool.join()
            t2 = time.time()
            print("所用时间为{}".format(t2 - t1))
        return open_list

    def get_port(self, ports):
        """
        简易扫描器，后期继续优化
        :param ports:
        :return:
        """
        try:
            time.sleep(random() * 2)
            print("扫描{}!!!".format(ports))
            socket.setdefaulttimeout(2)
            client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            client_socket.connect((self.ip, int(ports)))
            open_list.append(ports)
        except:
            pass
        finally:
            client_socket.close()
